<script setup lang="ts">
import {ref, watch, nextTick} from 'vue'
import {QuestionControllerService, SetDetailVO} from "../../../../../generated";
import {useRoute, useRouter} from "vue-router";
import QuestionList from "../../../studyPlan/components/QuestionList.vue";

const props = withDefaults(defineProps<{
  showTab?: boolean,
  set?: SetDetailVO,
  mode?: string
}>(), {
  showTab: false,
  mode: ''
})

const emit = defineEmits(['update:showTab'])

const router = useRouter();
const route = useRoute();

const visible = ref(props.showTab)
const showTags = ref(false)

const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const finished = ref(false)
const questions = ref<any[]>([])
const total = ref(0)

// 监听 props.showTab 的变化
watch(() => props.showTab, (newVal) => {
  visible.value = newVal
})

// 监听 visible 的变化
watch(() => visible.value, (newVal) => {
  emit('update:showTab', newVal)
  if (!props.mode) {
    // 打开时初始化
    nextTick(() => {
      loadMore()
    })
  }
})

const handleClickTitle = () => {
  if (props.mode) {
    router.push('/studyplan/' + route.query.envId)
  } else {
    router.push('/problem')
  }
}

// 加载更多数据
const loadMore = async () => {
  if (loading.value || finished.value || !visible.value) return

  loading.value = true
  try {
    if (!props.mode) {
      const res = await QuestionControllerService.pageQuestionsUsingPost({
        currentPage: pageNum.value,
        pageSize: pageSize.value
      })

      if (res.code === 0 && res.data) {
        const newQuestions = res.data.records || []
        questions.value.push(...newQuestions)
        total.value = res.data.total || 0

        if (questions.value.length >= total.value) {
          finished.value = true
        } else {
          pageNum.value++
        }
      }
    }
  } catch (error) {
    console.error('加载题目失败:', error)
  } finally {
    loading.value = false
  }
}

// 定义难度映射的类型
interface DifficultyInfo {
  type: string;
  label: string;
}

type DifficultyMap = {
  [key: number]: DifficultyInfo;
}

// 添加题目难度映射
const difficultyMap: DifficultyMap = {
  0: {type: 'success', label: '简单'},
  1: {type: 'warning', label: '中等'},
  2: {type: 'danger', label: '困难'}
}

// 添加跳转到题目详情的方法
const handleQuestionClick = (questionId: string) => {
  visible.value = false
  router.push(`/question/detail/${questionId}`)
}
</script>

<template>
  <el-drawer
      v-model="visible"
      direction="ltr"
      size="600px"
  >
    <template #header>
      <span class="submission-title" @click="handleClickTitle">
        {{ props.mode ? props.set?.title : '题库' }} >
      </span>
    </template>
    <template #default>
      <div class="drawer-content">
        <div v-if="props.mode && props.set">
          <QuestionList
              v-for="group in props.set.groups"
              :key="group.title"
              :title="group.title"
              :questions="group.questions"
              :show-tags="showTags"
          />
        </div>
        <div v-else
             class="infinite-list"
             v-infinite-scroll="loadMore"
             :infinite-scroll-disabled="loading || finished"
             :infinite-scroll-delay="200"
             :infinite-scroll-distance="10"
             :infinite-scroll-immediate="true"
        >
          <div class="question-list">
            <div v-for="question in questions"
                 :key="question.id"
                 class="question-item"
                 :class="{ 'active': question.id === route.params.id }"
                 @click="handleQuestionClick(question.id)"
            >
              <div class="question-info">
                <span class="question-title">{{ question.title }}</span>
                <el-tag
                    :type="difficultyMap[question.difficulty].type"
                    size="small"
                    class="difficulty-tag"
                >
                  {{ difficultyMap[question.difficulty].label }}
                </el-tag>
              </div>
            </div>
          </div>
          <div v-if="loading" class="loading">
            <el-icon class="loading-icon">
              <Loading/>
            </el-icon>
            加载中...
          </div>
          <div v-if="finished" class="no-more">
            没有更多了
          </div>
        </div>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped>
.question-list {
  margin-top: 10px;
}

.submission-title {
  color: #1A1A1A;
  font-size: 20px;
  cursor: pointer;
}

.drawer-content {
  height: 100%;
  overflow: hidden;
}

.infinite-list {
  height: 100%;
  overflow-y: auto;
}

.question-list {
  display: flex;
  flex-direction: column;
}

.question-item {
  padding: 0 16px;
  height: 44px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.question-item:nth-child(odd) {
  background-color: #FAFAFA;
}

.question-item:hover {
  background-color: #f5f7fa;
}

.question-item.active {
  background-color: #ecf5ff !important;
  color: #409eff;
}

.question-item.active .question-title {
  color: #409eff;
}

.question-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.question-title {
  font-size: 14px;
  color: #1a1a1a;
  font-weight: 500;
}

.difficulty-tag {
  font-size: 12px;
}

.loading, .no-more {
  text-align: center;
  padding: 10px 0;
  color: #909399;
  font-size: 14px;
}

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-icon {
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>